import { useState, useEffect, useCallback } from 'react';
import { message } from 'antd';
import { authApi, permissionApi } from '../../services';
import { RbacUtils } from '../../services/cloud/api/rbacUtils';
import type { User, Permission } from '../../types/rbac';
import type { PermissionListParams } from '../../services/cloud/api/permissionApi';

// 权限表单数据类型 - 与后端DTO保持一致
export interface PermissionFormData {
  id?: string;
  code: string;
  name: string;
  description?: string;
  type: string; // "menu"-菜单，"button"-按钮，"api"-API
  category: string; // 权限分类，如 'system', 'user', 'role' 等
  parentId?: string;
  path?: string;
  method?: string;
  icon?: string;
  component?: string;
  redirect?: string;
  hidden?: boolean;
  alwaysShow?: boolean;
  isBuiltin?: boolean;
  priority?: number;
  sort?: number;
  status?: number; // 1-启用，0-禁用
}

// 权限查询参数类型
export interface PermissionQueryParams {
  page?: number;
  size?: number;
  name?: string;
  code?: string;
  type?: 'menu' | 'button' | 'api';
  parentId?: string;
  status?: number; // 1-启用，0-禁用
  sortBy?: string;
  sortOrder?: 'asc' | 'desc';
}

// 权限列表Hook
export const usePermissions = (initialParams?: PermissionQueryParams) => {
  const [permissions, setPermissions] = useState<Permission[]>([]);
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [params, setParams] = useState<PermissionQueryParams>(initialParams || {});

  const loadPermissions = useCallback(async (queryParams?: PermissionQueryParams) => {
    setLoading(true);
    try {
      const searchParams = { ...params, ...queryParams };
      const response = await permissionApi.getPermissions(searchParams);
      
      // 适配后端分页响应格式
      if (response.records) {
        setPermissions(response.records);
        setTotal(response.totalElements || 0);
      } else {
        // 兼容直接返回数组的情况
        setPermissions(Array.isArray(response) ? response : []);
        setTotal(Array.isArray(response) ? response.length : 0);
      }
      
      setParams(searchParams);
    } catch (error) {
      console.error('加载权限列表失败:', error);
      message.error('加载权限列表失败');
      setPermissions([]);
      setTotal(0);
    } finally {
      setLoading(false);
    }
  }, [params]);

  useEffect(() => {
    loadPermissions();
  }, []);

  return {
    permissions,
    loading,
    total,
    params,
    loadPermissions,
    setParams,
  };
};

// 权限详情Hook
export const usePermission = (id?: string) => {
  const [permission, setPermission] = useState<Permission | null>(null);
  const [loading, setLoading] = useState(false);

  const loadPermission = useCallback(async (permissionId: string) => {
    setLoading(true);
    try {
      const data = await permissionApi.getPermission(permissionId);
      setPermission(data);
    } catch (error) {
      console.error('加载权限详情失败:', error);
      message.error('加载权限详情失败');
      setPermission(null);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    if (id) {
      loadPermission(id);
    }
  }, [id, loadPermission]);

  return {
    permission,
    loading,
    loadPermission,
  };
};

// 权限操作Hook
export const usePermissionActions = () => {
  const [loading, setLoading] = useState(false);

  const createPermission = useCallback(async (data: PermissionFormData) => {
    setLoading(true);
    try {
      const result = await permissionApi.createPermission(data);
      message.success('创建权限成功');
      return result;
    } catch (error) {
      console.error('创建权限失败:', error);
      message.error('创建权限失败');
      throw error;
    } finally {
      setLoading(false);
    }
  }, []);

  const updatePermission = useCallback(async (id: string, data: Partial<PermissionFormData>) => {
    setLoading(true);
    try {
      const result = await permissionApi.updatePermission(id, data);
      message.success('更新权限成功');
      return result;
    } catch (error) {
      console.error('更新权限失败:', error);
      message.error('更新权限失败');
      throw error;
    } finally {
      setLoading(false);
    }
  }, []);

  const deletePermission = useCallback(async (id: string) => {
    setLoading(true);
    try {
      await permissionApi.deletePermission(id);
      message.success('删除权限成功');
    } catch (error) {
      console.error('删除权限失败:', error);
      message.error('删除权限失败');
      throw error;
    } finally {
      setLoading(false);
    }
  }, []);

  const batchDeletePermissions = useCallback(async (ids: string[]) => {
    setLoading(true);
    try {
      await permissionApi.batchDeletePermissions(ids);
      message.success(`成功删除 ${ids.length} 个权限`);
    } catch (error) {
      console.error('批量删除权限失败:', error);
      message.error('批量删除权限失败');
      throw error;
    } finally {
      setLoading(false);
    }
  }, []);

  const movePermission = useCallback(async (permissionId: string, targetParentId?: string, targetSort?: number) => {
    setLoading(true);
    try {
      await permissionApi.movePermission({
        permissionId,
        targetParentId,
        targetSort: targetSort || 0,
      });
      message.success('移动权限成功');
    } catch (error) {
      console.error('移动权限失败:', error);
      message.error('移动权限失败');
      throw error;
    } finally {
      setLoading(false);
    }
  }, []);

  const batchUpdateSort = useCallback(async (data: Array<{ id: string; sort: number }>) => {
    setLoading(true);
    try {
      await permissionApi.batchUpdateSort(data);
      message.success('更新排序成功');
    } catch (error) {
      console.error('更新排序失败:', error);
      message.error('更新排序失败');
      throw error;
    } finally {
      setLoading(false);
    }
  }, []);

  const checkPermissionCode = useCallback(async (code: string, excludeId?: string) => {
    try {
      const result = await permissionApi.checkPermissionCode(code, excludeId);
      return result.exists;
    } catch (error) {
      console.error('检查权限编码失败:', error);
      return false;
    }
  }, []);

  return {
    loading,
    createPermission,
    updatePermission,
    deletePermission,
    batchDeletePermissions,
    movePermission,
    batchUpdateSort,
    checkPermissionCode,
  };
};

// 权限树状态管理hook
export const usePermissionTree = (permissions: Permission[]) => {
  const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
  const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
  const [autoExpandParent, setAutoExpandParent] = useState(true);

  // 默认展开所有节点
  useEffect(() => {
    if (permissions.length > 0) {
      const allKeys = permissions.map(p => p.id);
      setExpandedKeys(allKeys);
    }
  }, [permissions]);

  const onExpand = (expandedKeysValue: React.Key[]) => {
    setExpandedKeys(expandedKeysValue as string[]);
    setAutoExpandParent(false);
  };

  const onSelect = (selectedKeysValue: React.Key[]) => {
    setSelectedKeys(selectedKeysValue as string[]);
  };

  const expandAll = () => {
    const allKeys = permissions.map(p => p.id);
    setExpandedKeys(allKeys);
    setAutoExpandParent(true);
  };

  const collapseAll = () => {
    setExpandedKeys([]);
    setAutoExpandParent(false);
  };

  return {
    selectedKeys,
    expandedKeys,
    autoExpandParent,
    onExpand,
    onSelect,
    expandAll,
    collapseAll,
    setSelectedKeys,
    setExpandedKeys,
  };
};

// 权限统计hook
export const usePermissionStats = () => {
  const [stats, setStats] = useState({
    total: 0,
    menuCount: 0,
    buttonCount: 0,
    apiCount: 0,
    rootCount: 0,
  });
  const [loading, setLoading] = useState(false);

  const loadStats = async () => {
    try {
      setLoading(true);
      // 调用真实的API获取统计数据
      const permissions = await permissionApi.getPermissions({});
      const permissionList = permissions.records || [];
      
      const total = permissionList.length;
      const menuCount = permissionList.filter((p: Permission) => p.type === 'menu').length;
      const buttonCount = permissionList.filter((p: Permission) => p.type === 'button').length;
      const apiCount = permissionList.filter((p: Permission) => p.type === 'api').length;
      const rootCount = permissionList.filter((p: Permission) => !p.parentId).length;
      
      setStats({ total, menuCount, buttonCount, apiCount, rootCount });
    } catch (error) {
      console.error('加载权限统计失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadStats();
  }, []);

  return {
    stats,
    loading,
    refresh: loadStats,
  };
};

// 导出权限类型（移除重复导出）

/**
 * 用户权限检查hook
 * 基于API的权限验证
 */
export const useUserPermissions = (user: User | null) => {
  const [loading, setLoading] = useState(false);
  
  /**
   * 检查单个权限
   */
  const checkPermission = useCallback(async (permissionCode: string, context?: any): Promise<boolean> => {
    if (!user) {
      return false;
    }

    // 首先使用前端缓存进行快速检查
    const quickCheck = RbacUtils.hasBasicPermission(user, permissionCode);
    if (quickCheck) {
      return true;
    }

    // 如果有上下文信息，需要通过API进行完整验证
    if (context) {
      try {
        setLoading(true);
        const result = await authApi.checkPermission({
          userId: user.id,
          permissionCode,
          context
        });
        return result.hasPermission;
      } catch (error) {
        console.error('权限验证失败:', error);
        return false;
      } finally {
        setLoading(false);
      }
    }

    return false;
  }, [user]);

  /**
   * 批量检查权限
   */
  const checkPermissions = useCallback(async (permissionCodes: string[], context?: any): Promise<Record<string, boolean>> => {
    if (!user) {
      return {};
    }

    try {
      setLoading(true);
      const result = await authApi.checkPermissions({
        userId: user.id,
        permissions: permissionCodes,
        context
      });
      return result;
    } catch (error) {
      console.error('批量权限验证失败:', error);
      return {};
    } finally {
      setLoading(false);
    }
  }, [user]);

  /**
   * 检查角色
   */
  const checkRole = useCallback(async (roleCode: string): Promise<boolean> => {
    if (!user) {
      return false;
    }

    // 先使用前端快速检查
    const quickCheck = RbacUtils.hasBasicRole(user, roleCode);
    if (quickCheck) {
      return true;
    }

    // 通过API进行验证
    try {
      const result = await authApi.checkRole({
        userId: user.id,
        roleCode
      });
      return result.hasRole;
    } catch (error) {
      console.error('角色验证失败:', error);
      return false;
    }
  }, [user]);

  return {
    loading,
    checkPermission,
    checkPermissions,
    checkRole,
    // 提供便捷的前端检查方法
    hasPermission: (permissionCode: string) => user ? RbacUtils.hasBasicPermission(user, permissionCode) : false,
    hasRole: (roleCode: string) => user ? RbacUtils.hasBasicRole(user, roleCode) : false,
    hasAnyPermission: (permissionCodes: string[]) => user ? RbacUtils.hasAnyPermission(user, permissionCodes) : false,
    hasAllPermissions: (permissionCodes: string[]) => user ? RbacUtils.hasAllPermissions(user, permissionCodes) : false,
    hasAnyRole: (roleCodes: string[]) => user ? RbacUtils.hasAnyRole(user, roleCodes) : false,
  };
};